package com.wn.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wn.pojo.User;
import com.wn.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yellow docker
 * @since 2023-07-18
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping("/list")
    public List<User> findUsers(){
        return userService.list();
    }

    @GetMapping("/page/{currentPage}/{pageSize}")
    public Map pageUsers(@PathVariable Integer currentPage,@PathVariable Integer pageSize){

        IPage<User> p = new Page<>(currentPage,pageSize);
        IPage<User> page = userService.page(p);

        long total = page.getTotal();
        List<User> records = page.getRecords();

        Map<String,Object> map = new HashMap<>();
        map.put("total",total);
        map.put("records",records);

        return map;

    }


    @PostMapping
    public String addUser(@RequestBody User user){
        boolean b = userService.saveOrUpdate(user);
        return b ? "add success" :"add error";
    }

    @PutMapping()
    public String updateUsers(@RequestBody User user){
        boolean b = userService.saveOrUpdate(user);
        return b ? "update success" :" update error";
    }

    @DeleteMapping("/{id}")
    public String findUsers(@PathVariable("id") Integer id) {
        boolean b = userService.removeById(id);
        return b ? "delete success" : " delete error";
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable("id") Integer id) {
        User user = userService.getById(id);
        return user;
    }
}
